const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');

// 自定义中间件
const notFound = require('./middlewares/notFound');
const errorHandler = require('./middlewares/errorHandler')

const {
  port,
  baseUrl
} = require('./config'); //配置

const db = require('./db'); //引入数据库模型

const app = express();

//设置body-parser中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use((cors())); //允许跨域
app.use(morgan('tiny'));


app.use(express.static('uploads'));

// 挂载路由
app.use(require('./routes/userRouter'));
app.use(require('./routes/newsRouter'));

// catch 404 and forward to error handler
app.use(notFound);

// error handler
app.use(errorHandler);

// 一次性同步数据库模型
db.sequelize.sync({
  force: false
}).then(() => {
  app.listen(port, () => {
    console.log(`${baseUrl}:${port}`);
  });
});